<%@ page import="com.party.core.model.system.TargetType" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="../include/tag.jsp" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <title>
        ${fn:length(fieldValue) > 0 ? '编辑' : '添加'}自定义表单信息
    </title>
    <%@include file="../include/commonFile.jsp" %>
    <link rel="stylesheet" href="${ctx}/css/common/list.css">
    <link rel="stylesheet" href="${ctx}/css/ui/system/member/member_form.css">
    <script type="text/javascript" src="${ctxStatic}/typeahead/typeahead.bundle.js"></script>
    <style>
        .member-cell {
            display: -webkit-box;
            display: -webkit-flex;
            display: -moz-box;
            display: -ms-flexbox;
            display: flex;
            width: 100%;
            -webkit-box-align: center;
            -webkit-align-items: center;
            -moz-box-align: center;
            -ms-flex-align: center;
            align-items: center;
            -webkit-box-pack: start;
            -webkit-justify-content: flex-start;
            -moz-box-pack: start;
            -ms-flex-pack: start;
            justify-content: flex-start;
        }

        .member-cell .member-logo {
            display: inline-block;
            /*float: left;*/
            width: 30px;
            height: 30px;
            -webkit-border-radius: 50%;
            border-radius: 50%;
            line-height: 50px;
            -webkit-background-size: cover;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }

        .member-cell .member-name {
            -webkit-box-flex: 1;
            -moz-box-flex: 1;
            -ms-flex: 1;
            -webkit-flex: 1;
            flex: 1;
            line-height: 30px;
            padding-left: 5px;
            display: inline-block;
            text-align: left;
        }

        .member-cell .member-logo-img {
            width: 30px;
            height: 30px;
            -webkit-border-radius: 50%;
            border-radius: 50%;
        }

        .layui-form-label {
            width: 75px !important;
        }
    </style>
</head>
<body>
<!--头部-->
<%@include file="../include/header.jsp" %>
<div class="index-outside">
    <%@include file="../include/sidebar.jsp" %>
    <!--内容-->
    <section>
        <div class="section-main">
            <!-- 正文请写在这里 -->
            <div class="layui-tab layui-tab-brief">
                <div class="layui-tab-content">
                    <%--基本信息--%>
                    <div class="layui-tab-item layui-show">
                        <form id="myForm" class="layui-form mt20" method="post"
                              action="${ctx}/member/membermgmt/xzgs/saveMemberFieldValue.do">
                            <input type="hidden" name="memberId" value="${memberId}">
                            <input type="hidden" name="id" value="${projectId}">
                                <c:forEach items="${fieldName}" var="item" varStatus="i">
                                    <c:if test="${item.type == 'input' || item.type == 'qq' || item.type == 'tel' || item.type == 'email'}">
                                        <div class="layui-form-item">
                                            <div class="layui-inline">
                                                <label class="layui-form-label">${item.title}
                                                    <c:if test="${item.required}">
                                                        <span class="f-verify-red">*</span>
                                                    </c:if>
                                                </label>
                                                <div class="layui-input-inline itemkc" id="${item.id}" custom="input">
                                                    <input class="layui-input" type="text" id="${item.id}" lay-verify ="${item.category}"
                                                           placeholder="${empty item.description ? '请输入': item.description}"
                                                           lay-verify ="${item.category}"
                                                           value="" >
                                                </div>
                                            </div>
                                        </div>
                                    </c:if>
                                    <c:if test="${item.type == 'textarea'}">
                                        <div class="layui-form-item">
                                            <div class="layui-inline">
                                                <label class="layui-form-label">${item.title}
                                                    <c:if test="${item.required}">
                                                        <span class="f-verify-red">*</span>
                                                    </c:if>
                                                </label>
                                                <div class="layui-input-inline itemkc" id="${item.id}"
                                                     style="width: 300px; height: 50px"
                                                     custom="textarea">
                                                    <textarea class="layui-input" type="textarea" style="resize:none"
                                                           id="textarea_${i.index}"
                                                           placeholder="${empty item.description ? '请输入': item.description}">
                                                    </textarea>
                                                </div>
                                            </div>
                                        </div>
                                    </c:if>
                                    <c:if test="${item.type =='radio'}">
                                        <div class="layui-form-item">
                                            <div class="layui-inline">
                                                <label class="layui-form-label">${item.title}
                                                    <c:if test="${item.required}">
                                                        <span class="f-verify-red">*</span>
                                                    </c:if>
                                                </label>
                                                <div class="layui-input-inline itemkc" id="${item.id}" custom="radio">
                                                    <c:forEach items="${item.subItemNames}" var="subItem" varStatus="j">
                                                        <input  type="radio" name="radio_${i.index}"  value="${subItem}" title="${subItem}">
                                                    </c:forEach>
                                                </div>
                                            </div>
                                        </div>
                                    </c:if>
                                    <c:if test="${item.type =='date'}">
                                        <div class="layui-form-item">
                                            <div class="layui-inline">
                                                <label class="layui-form-label">${item.title}
                                                    <c:if test="${item.required}">
                                                        <span class="f-verify-red">*</span>
                                                    </c:if>
                                                </label>
                                                <div class="layui-input-inline itemkc" id="${item.id}"
                                                     custom = "date">
                                                    <input type="text" class="layui-input"
                                                           name="datetime_${i.index}"
                                                           placeholder="${empty item.description ? '请输入': item.description}"
                                                           >
                                                </div>
                                            </div>
                                        </div>
                                    </c:if>
                                    <c:if test="${item.type =='number'}">
                                        <div class="layui-form-item">
                                            <div class="layui-inline">
                                                <label class="layui-form-label">${item.title}
                                                    <c:if test="${item.required}">
                                                        <span class="f-verify-red">*</span>
                                                    </c:if>
                                                </label>
                                                <div class="layui-input-inline itemkc" id="${item.id}" custom="number">
                                                    <input type="number" class="layui-input"
                                                           placeholder="${empty item.description
                                                           ? '请输入': item.description}"
                                                           >
                                                </div>
                                            </div>
                                        </div>
                                    </c:if>
                                    <c:if test="${item.type =='checkbox'}">
                                        <div class="layui-form-item">
                                            <div class="layui-inline">
                                                <label class="layui-form-label">${item.title}
                                                    <c:if test="${item.required}">
                                                        <span class="f-verify-red">*</span>
                                                    </c:if>
                                                </label>
                                                <div class="layui-input-inline itemkc" id="${item.id}" custom="checkbox">
                                                    <c:forEach items="${item.subItemNames}" var="subItem" varStatus="j">
                                                        <input class="layui-input" type="checkbox"
                                                               name="box_${i.index}" value="${subItem}" title="${subItem}">
                                                    </c:forEach>
                                                </div>
                                            </div>
                                        </div>
                                    </c:if>
                                    <c:if test="${item.type =='select'}">
                                        <div class="layui-form-item">
                                            <div class="layui-inline">
                                                <label class="layui-form-label">${item.title}
                                                    <c:if test="${item.required}">
                                                        <span class="f-verify-red">*</span>
                                                    </c:if>
                                                </label>
                                                <div class="layui-input-inline itemkc" id="${item.id}"
                                                     index =${i.index} custom="select">
                                                    <select id="${item.id}"
                                                            lay-filter="select_${i.index}"
                                                            name="select_${i.index}">
                                                        <option value="">选择${item.title}</option>
                                                        <c:forEach items="${item.subItemNames}"
                                                                   var="subItem" varStatus="j">
                                                            <option value="ops_${i.index}_${j.index}" name="ops_${i.index}">${subItem}</option>
                                                        </c:forEach>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </c:if>
                                    <c:if test="${item.type =='image'}">
                                        <c:set var="maxNumber" value="${item.maxNumber}"></c:set>
                                        <c:set var="isSetMultiple" value="${item.isSetMultiple}"></c:set>
                                        <div class="layui-form-item">
                                            <div class="layui-inline">
                                                <label class="layui-form-label">${item.title}
                                                    <c:if test="${item.required}">
                                                        <span class="f-verify-red">*</span>
                                                    </c:if>
                                                </label>
                                                <div class="cover-content itemkc" id="${item.id}" custom="img">
                                                    <a class="layui-btn layui-btn-danger" id="sel_pic_img">+添加图片</a>
                                                </div>
                                            </div>
                                        </div>
                                    </c:if>
                                </td>
                            </tr>
                        </c:forEach>
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label"></label>
                                    <div class="layui-input-inline">
                                        <a href="javascript:void(0)" class="layui-btn layui-btn-danger"
                                           lay-submit
                                           lay-filter="myForm">立即提交</a>
                                        <a href="${ctx}/member/membermgmt/list.do"
                                           class="layui-btn layui-btn-primary">取消</a>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div><!--底部-->
        <%@include file="../include/footer.jsp" %>
    </section>
</div>
<script>
    //存储上传图片路径
    var saveFiles = [];
    //已选图片数量
    var selImgLength = 0;
    //
    var lastImgLength = 0;

    var feildValueArray = [];

    var maxNumber = ${empty maxNumber ? 1 : maxNumber}
    $(function () {
        $('#sel_pic_img').click(function () {

            if (${empty isSetMultiple}) {
                lastImgLength = 1;
            } else {
                if (selImgLength > maxNumber) {
                    return false;
                } else {
                    if (selImgLength) {
                        lastImgLength = maxNumber - selImgLength;
                    } else {
                        lastImgLength = maxNumber;
                    }
                }
            }
            txz.openSelImg({
                min: 1,
                max: lastImgLength,
                info: '建议尺寸：120x120',
                type: '<%=TargetType.LOGO.getCode()%>',
                cb: function (imgs) {
                    // $('#pic').val(imgs[0].path);
                    selImgLength = parseInt(selImgLength) + parseInt(imgs.length);

                    var array = new Array();
                    $(imgs).each(function (i,that) {
                        var path = $(that)[0].path;
                        saveFiles.push($(that)[0].path)
                        array.push("<span onclick =removeAllImg(this) img = '"+path+"'  class='cover-img' style='background-image:url("+path+")'>" + "</span>")
                    })
                    // console.log(selImgLength)
                    $($('#sel_pic_img').parent()).append(array)
                    // console.log(saveFiles.join(","))
                }
            })
        })

        var form, element;

        layui.use(['form', 'laydate', 'element'], function () {
            form = layui.form, laydate = layui.laydate, element = layui.element;

            var laydate = layui.laydate;

            //自定义验证规则
            form.verify({
                FIELD_MOBILE: function (value) {
                    if (!util.checkMobile(value)) {
                        return '电话格式不对';
                    }
                },
                FIELD_QQ: function (value) {
                    if (!util.checkQQ(value)) {
                        return "QQ格式不对"
                    }
                },
                FIELD_EMAIL: function (value) {
                    if (!util.checkEmail(value)) {
                        return "Email格式不对"
                    }
                }
            });
            var dataFeild = {
                id : '${projectId}',
                isNew : '${isNew}',
                memberId : '${memberId}'
            }

            // form.on('select', function (data) {
            //     console.log(data.value);
            //     console.log(data.elem[data.elem.selectedIndex].text);
            // });

            <c:forEach items="${fieldValue}" var="value">
                feildValueArray.push('${value.fieldValue}')
            </c:forEach>
            // console.log(feildValueArray)

            $(".itemkc").each(function (i,that) {
                var attr = $(this).attr("custom");
                if (attr === 'date') {
                    var elm = 'input[name=datetime_'+i+']';
                    var datetime = {
                        elem: elm
                    };
                    $(elm).val(feildValueArray[i])
                    laydate.render(datetime)
                } else if (attr == 'select') {
                    var selectId = '#'+that.id +' select'
                    var selectValue = feildValueArray[i];

                    if (util.isValid(selectValue)) {
                        $(selectId).each(function () {
                            $(this).children("option").each(function () {
                                if ($(this).text() == selectValue) {
                                    $(this).attr("selected", "selected");
                                }
                            })
                        })
                    }
                    form.render("select")
                } else  if (attr == 'radio') {
                    var  choose = feildValueArray[i];
                    if (util.isValid(choose)) {
                        var radioName = 'input[name='+'radio_'+i+']';
                        $(radioName).each(function () {

                            if (this.value == choose) {
                                $(this).prop("checked",true);
                            }
                        })
                    }
                    form.render()
                } else  if (attr == 'checkbox') {
                    var boxName = 'input:checkbox[name=box_'+i+']';
                    var boxValue = feildValueArray[i];
                    if (util.isValid(boxValue)) {
                        var values = boxValue.split(",");
                        if (values.length == 1) {
                            $(boxName).each(function () {
                                if (this.value == values[0]) {
                                    $(this).prop("checked",true);
                                }
                            })
                        } else if (values.length > 1) {
                            for (var j = 0; j < values.length; j++) {
                                $(boxName).each(function () {
                                    if (this.value == values[j]) {
                                        $(this).prop("checked",true);
                                    }
                                })
                            }
                        }
                    }
                    form.render()
                } else  if (attr == 'img') {
                    var imgPath = feildValueArray[i];

                    var array = new Array();
                    if (imgPath) {

                        var values = imgPath.split(",");
                        for (var j = 0; j < values.length; j++) {
                            var path = values[j];
                            // console.log(path)
                            selImgLength = j +1;
                            lastImgLength = ${maxNumber} -1;
                            saveFiles.push(path)
                            array.push("<span onclick =removeAllImg(this) img = '"+path+"'  class='cover-img' style='background-image:url("+path+")'>" + "</span>")
                        }
                        $($('#sel_pic_img').parent()).append(array)
                    }

                } else  if (attr == 'textarea') {
                    var id = '#'+'textarea_'+i
                    if (util.isValid(feildValueArray[i])) {
                        var  val = feildValueArray[i];
                        console.log(val);
                        val = val.replace(/<br\/>/g,'\n')
                        $(id).val(val)
                    }

                } else {
                    if (util.isValid(feildValueArray[i])) {
                        $($(this).find("input")[0]).val(feildValueArray[i])
                    }

                }

            });

            //监听提交
            form.on('submit(myForm)', function (data) {

                $(".itemkc").each(function (i,that) {

                    var fieldId = 'infoItems'+'['+i+']'+'.fieldId';
                    var sort = 'infoItems'+'['+i+']'+'.sort';
                    var fieldValue = 'infoItems'+'['+i+']'+'.fieldValue';
                    var memberId = 'infoItems'+'['+i+']'+'.memberId';

                    dataFeild[fieldId] = that.id;
                    dataFeild[sort] = i +1;

                    var customType = $(this).attr("custom");
                    // console.log(customType)
                    if (customType == 'radio') {
                        var radioName = 'input[name='+'radio_'+i+']'+':checked'
                        var radioFeild = $(this).find(radioName).val();

                        if (typeof  radioFeild == 'undefined') {
                            radioFeild = '';
                        }
                        dataFeild[fieldValue] = radioFeild;
                    } else if (customType === 'checkbox') {
                        var boxFeild = [];
                        var boxName = 'input:checkbox[name=box_'+i+']:checked'
                        $(boxName).each(function() {
                            boxFeild.push($(this).val());
                        });
                        // console.log(boxFeild.join(","));
                        dataFeild[fieldValue] = boxFeild.join(",");
                    } else if (customType == 'select') {
                        var id = '#'+that.id +' option:selected'
                        // console.log($(id).text());
                        dataFeild[fieldValue] = $(id).text();
                    } else if (customType == 'img') {
                        console.log(saveFiles)
                        dataFeild[fieldValue] = saveFiles.join(",");
                    } else if (customType == 'textarea') {
                        var id = '#'+'textarea_'+i

                        var str = $(id).val();
                        str = str.replace(/(^\s*)|(\s*$)/g, "");
                        // console.log(str);
                        str = str.replace(/[\r\n]/g,"");
                        dataFeild[fieldValue] = str;
                    }
                    else {
                        dataFeild[fieldValue] = $(this).find("input")[0].value;
                    }

                });

                txz.submitObject(data.elem, function (callBack) {
                    var action = $("#myForm").attr("action");
                    $.post(action, dataFeild, function (res) {
                        typeof callBack === 'function' && callBack();
                        if (res.success) {
                            util.layerMsgSuccess("自定义信息提交成功", function () {
                                var ref = '';
                                if (document.referrer.length > 0) {
                                    ref = document.referrer;
                                }
                                if (ref.length > 0) {
                                    if (ref.indexOf("pageNo") != -1) {
                                        location.href = ref;
                                    } else {
                                        ref = ref + "?pageNo=${pageNo}"
                                        location.href = ref;
                                    }
                                } else {
                                    location.href = "${ctx}/member/membermgmt/list.do";
                                }
                            });
                        } else {
                            util.layerMsgError(res.description)
                        }
                    });
                })
                return false;
            });

        });
    })

    function removeAllImg(that) {
        $(that).remove();
        $(that).attr("img");
        var number = saveFiles.indexOf($(that).attr("img"));
        // console.log(number);
        if (number > -1) {
            saveFiles.splice(number, 1)
            selImgLength = selImgLength -1;
        }
    }
</script>
<script type="text/javascript">
    txz.initHeader({
        nav: [{
            name: '会员管理',
            href: '${ctx}/member/membermgmt/list.do'
        }, {
            name: '${fn:length(fieldValue) > 0  ? '编辑' : '添加'}自定义表单信息',
            curr: true
        }],
        btns: [{
            name: '返回',
            href: 'javascript:history.back();',
            icon: 'back'
        }]
    });
</script>
</body>
</html>